﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rss.Domain;
using System.IO;
using System.Threading.Tasks;

namespace RssApp.Parser
{

    /// <summary>
    /// OSC解析
    /// </summary>
    public class OscParser : BlogParserBase, Rss.Infrastructure.IBlogParser
    {
        /// <summary>
        /// 返回博客列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Blog> TryCatchBlogs(Rss.Domain.RssInfo rss)
        {
            List<Blog> list = new List<Blog>();
            string strRssXml = base.TryGetRss(rss);
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Rss.Domain.ValueObject.Rss));
            using (StringReader sr = new StringReader(strRssXml))
            {
                object o = xs.Deserialize(sr);
                Rss.Domain.ValueObject.Rss rssObj = (Rss.Domain.ValueObject.Rss)o;
                sr.Dispose();
                foreach (var item in rssObj.channel.items)
                {
                    Blog blog = new Blog();
                    blog.Title = item.title;
                    blog.Url = item.link;
                    blog.Summary = item.description;
                    blog.Category = item.category;
                    list.Add(blog);
                }
            }
            return list;
        }

        /// <summary>
        /// 异步：返回博客列表
        /// </summary>
        /// <param name="rss"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Blog>> TryCatchBlogsAsync(RssInfo rss)
        {
            string strRssXml = await base.TryGetRssAsync(rss);
            return await Task.Run<IEnumerable<Blog>>(() =>
              {
                  List<Blog> list = new List<Blog>();
                  System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Rss.Domain.ValueObject.Rss));
                  using (StringReader sr = new StringReader(strRssXml))
                  {
                      object o = xs.Deserialize(sr);
                      Rss.Domain.ValueObject.Rss rssObj = (Rss.Domain.ValueObject.Rss)o;
                      foreach (var item in rssObj.channel.items)
                      {
                          Blog blog = new Blog();
                          blog.Title = item.title;
                          blog.Url = item.link;
                          blog.Summary = item.description;
                          blog.Category = item.category;
                          list.Add(blog);
                      }
                      return list;
                  }
              });
        }
    }
}